package org.example.executor;

import org.example.config.Configuration;
import org.example.executor.statement.StatementHandler;
import org.example.mapping.BoundSql;
import org.example.mapping.MappedStatement;
import org.example.session.ResultHandler;
import org.example.session.RowBounds;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class SimpleExecutor extends BaseExecutor {

    public SimpleExecutor(Configuration configuration) {
        super(configuration);
    }


    protected <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds,ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        Statement stmt = null;
        try {
            Configuration configuration = ms.getConfiguration();
            StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
            //设置参数
            stmt = prepareStatement(handler);
            return handler.query(stmt, resultHandler);
        }catch (Exception e){
          e.printStackTrace();
          throw new RuntimeException(e.getMessage());
        } finally {
            closeStatement(stmt);
        }
    }

    private void closeStatement(Statement stmt) {
        try {
            stmt.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private Statement prepareStatement(StatementHandler handler) throws SQLException {
        Statement stmt;
        Connection connection = getConnection();
        stmt = handler.prepare(connection);
        //设置参数
        handler.parameterize(stmt);
        return stmt;
    }

    private Connection getConnection() throws SQLException {
        return configuration.getEnironment().getDataSource().getConnection();
    }


}
